import { Injectable, Inject, HttpStatus, } from "@nestjs/common";
import { JwtPayload } from "./interfaces/jwt.interface";
import { UserService } from "../user/user.service";
import { JwtService } from "@nestjs/jwt";
import { ApiResponse, ApiException } from "../../CoreModule/exception/api.exception";
import { ApiErrorCode } from "../../ShareModule/enums/api-error-code";
import { Repository } from "typeorm";
import { TokenEntity } from "../../ShareModule/entities/token.entity";

@Injectable()
export class AuthService{
    constructor(
        private readonly UserService:UserService,private readonly jwtService:JwtService,
        @Inject('AuthProviderToken') private readonly TokenRepository:Repository<TokenEntity>
    ){}

    async createToken(userName:string):Promise<any>{
        const user:JwtPayload = {userName:userName};
        return await this.jwtService.sign(user);
    }

    async validateUser(payload:JwtPayload):Promise<any>{
        return await this.UserService.findOne({userName:payload.userName});
    }

    async validateToken(token:string):Promise<any>{
        return await this.TokenRepository.findOne({token});
    }

    async login(loginInfo:any){
        const user = await this.UserService.findOne({userName:loginInfo.userName,password:loginInfo.password});

        if(user){
            const token:string = this.jwtService.sign({userName:user.userName});
            const oldRecord = await this.TokenRepository.findOne({uid:user.id});
            if(oldRecord) await this.TokenRepository.remove(oldRecord);
            await this.TokenRepository.save({token,uid:user.id,userName:user.userName});

            return {...user,token};
        }

        throw new ApiException('用户不存在',ApiErrorCode.NO_USER,HttpStatus.BAD_REQUEST);
    }

    async logout(user:any){
        const oldRecord = await this.TokenRepository.findOne({uid:user.id});
        if(oldRecord) await this.TokenRepository.remove(oldRecord);
        return "退出成功";
    }
}